package servlet.admin;

import com.alibaba.fastjson.JSON;
import pojo.Result;
import pojo.User;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/admin/getUserByIdServlet")
public class GetUserByIdServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取用户ID参数
        String userIdParam = request.getParameter("userId");
        if (userIdParam == null || userIdParam.isEmpty()) {
            response.setContentType("application/json;charset=UTF-8");
            Result result = Result.error("用户ID不能为空");
            response.getWriter().write(JSON.toJSONString(result));
            return;
        }

        int userId;
        try {
            userId = Integer.parseInt(userIdParam);
        } catch (NumberFormatException e) {
            response.setContentType("application/json;charset=UTF-8");
            Result result = Result.error("用户ID格式不正确");
            response.getWriter().write(JSON.toJSONString(result));
            return;
        }

        // 获取用户信息
        User user = userService.getUserById(userId);

        response.setContentType("application/json;charset=UTF-8");

        if (user != null) {
            Result result = Result.success(user);
            response.getWriter().write(JSON.toJSONString(result));
        } else {
            Result result = Result.error("用户不存在");
            response.getWriter().write(JSON.toJSONString(result));
        }
    }
}
